<script setup lang="ts">
import { computed, onMounted, reactive, ref, shallowRef, watch } from 'vue';
import { useBoolean } from '@sa/hooks';
import { useCopyProperties, useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';
import { enableStatusOptions } from '@/constants/business';
import { fetchAddRole, fetchGetMenuTree, fetchGetRoleInfo, fetchUpdateRole } from '@/service/api';

defineOptions({
  name: 'RoleOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.System.Role | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: $t('page.manage.role.addRole'),
    edit: $t('page.manage.role.editRole')
  };
  return titles[props.operateType];
});

const model: Api.System.RoleEditModel = reactive(createDefaultModel());

function createDefaultModel(): Api.System.RoleEditModel {
  return {
    id: null,
    roleName: '',
    roleKey: '',
    roleSort: 10,
    remarks: '',
    menuIds: [] as number[],
    status: null,
    home: 'home'
  };
}

type RuleKey = Exclude<keyof Api.System.RoleEditModel, 'id' | 'remarks' | 'menuIds' | 'home'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  roleName: defaultRequiredRule,
  roleKey: defaultRequiredRule,
  roleSort: defaultRequiredRule,
  status: defaultRequiredRule
};

const roleId = computed(() => props.rowData?.id || -1);

const isEdit = computed(() => props.operateType === 'edit');

async function handleInitModel() {
  Object.assign(model, createDefaultModel());

  if (props.operateType === 'edit' && props.rowData) {
    // 获取详情
    const { data } = await fetchGetRoleInfo(roleId.value);
    Object.assign(
      model,
      useCopyProperties(data, 'id', 'roleName', 'roleKey', 'roleSort', 'remarks', 'menuIds', 'home', 'status')
    );
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();
  // request
  let success: boolean = false;
  if (props.operateType === 'add') {
    const { error } = await fetchAddRole(model);
    if (!error) success = true;
  } else if (props.operateType === 'edit') {
    const { error } = await fetchUpdateRole(model);
    if (!error) success = true;
  }

  if (success) {
    window.$message?.success($t('common.updateSuccess'));
    closeDrawer();
    emit('submitted');
  }
}

const tree = shallowRef<Api.System.MenuTree[]>([]);
/** 菜单页面列表 */
const pageOptions = ref<CommonType.Option<string>[]>([]);
// 获取菜单树
async function getMenuTree() {
  const { error, data } = await fetchGetMenuTree();

  if (!error) {
    tree.value = data;

    pageOptions.value.push({
      label: 'home',
      value: 'home'
    });
  }
}

watch(visible, () => {
  if (visible.value) {
    // 加载菜单数据
    getMenuTree();
    handleInitModel();
    restoreValidation();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" display-directive="show" :width="360">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules">
        <NFormItem :label="$t('page.manage.role.roleName')" path="roleName">
          <NInput v-model:value="model.roleName" :placeholder="$t('page.manage.role.form.roleName')" />
        </NFormItem>
        <NFormItem :label="$t('page.manage.role.roleCode')" path="roleKey">
          <NInput v-model:value="model.roleKey" :placeholder="$t('page.manage.role.form.roleCode')" />
        </NFormItem>
        <NFormItem label="排序" path="roleSort">
          <NInputNumber v-model:value="model.roleSort" :step="5" placeholder="请选择排序" />
        </NFormItem>

        <NFormItem :label="$t('page.manage.role.roleDesc')" path="roleDesc">
          <NInput v-model:value="model.remarks" :placeholder="$t('page.manage.role.form.roleDesc')" />
        </NFormItem>
        <NFormItem :label="$t('page.manage.role.roleStatus')" path="status">
          <NRadioGroup v-model:value="model.status">
            <NRadio v-for="item in enableStatusOptions" :key="item.value" :value="item.value" :label="$t(item.label)" />
          </NRadioGroup>
        </NFormItem>
        <!--
 <NFormItem label="权限范围" path="status">
          <NSelect
            v-model:value="model.home"
            :options="pageOptions"
            :placeholder="$t('page.manage.user.form.userRole')"
          />
        </NFormItem> 
-->
        <!--
 <NFormItem label="首页" path="status">
          <NSelect
            v-model:value="model.home"
            :options="pageOptions"
            :placeholder="$t('page.manage.user.form.userRole')"
          />
        </NFormItem>
        <NFormItem label="菜单权限">
          <NTree
            v-model:checked-keys="model.menuIds"
            :data="tree"
            key-field="id"
            checkable
            expand-on-click
            virtual-scroll
            block-line
            class="h-280px"
          />
        </NFormItem> 
-->
      </NForm>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
